﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using Mayando.Web.Controllers;
using Mayando.Web.Extensions;
using Mayando.Web.Models;

namespace Mayando.Web.Infrastructure
{
    /// <summary>
    /// Blocks HTTP POST requests when in demo mode.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public sealed class BlockHttpPostInDemoModeAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (SiteData.GlobalDemoMode)
            {
                if (!string.Equals("get", filterContext.HttpContext.Request.HttpMethod, StringComparison.OrdinalIgnoreCase))
                {
                    // In demo mode, only allow HTTP GET. Redirect to the previous or home page for any other request.
                    if (filterContext.RequestContext.HttpContext.Request.UrlReferrer != null)
                    {
                        filterContext.Result = new RedirectResult(filterContext.RequestContext.HttpContext.Request.UrlReferrer.AbsoluteUri);
                    }
                    else
                    {
                        var routeValues = new RouteValueDictionary(new { controller = HomeController.ControllerName, action = ActionName.Index.ToActionString() });
                        filterContext.Result = new RedirectToRouteResult(routeValues);
                    }
                }
            }
        }
    }
}